package com.hdu.careerplan.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hdu.careerplan.configuration.FilepathConfiguration;
import com.hdu.careerplan.enums.CommandCode;
import com.hdu.careerplan.enums.CommandPatternEnum;
import com.hdu.careerplan.mapper.CompetenceInfoMapper;
import com.hdu.careerplan.mapper.DirectionRecommendationMapper;
import com.hdu.careerplan.mapper.PositionRecommendationMapper;
import com.hdu.careerplan.pojo.dto.CityJobChoiceListDTO;
import com.hdu.careerplan.pojo.entity.CompetenceInfo;
import com.hdu.careerplan.pojo.entity.DirectionRecommendation;
import com.hdu.careerplan.pojo.entity.PositionRecommendation;
import com.hdu.careerplan.pojo.pythonData.CompanyInfoData;
import com.hdu.careerplan.pojo.pythonData.CompanyListData;
import com.hdu.careerplan.pojo.pythonData.SalaryData;
import com.hdu.careerplan.service.RecommendService;
import com.hdu.careerplan.util.PythonJsonUtil;
import com.hdu.careerplan.util.PythonProcessUtil;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class RecommendServiceImpl implements RecommendService {

    @Resource
    private PositionRecommendationMapper positionRecommendationMapper;

    @Resource
    private DirectionRecommendationMapper directionRecommendationMapper;

    @Resource
    private CompetenceInfoMapper competenceInfoMapper;

    @Resource
    private MongoTemplate mongoTemplate;



    /**
     * 一个城市不同岗位的数据，和一个岗位不同城市的数据
     * @param flag 0：一个城市不同岗位的数据；1：一个岗位不同城市的数据
     * @param cityJobChoiceListDTO 城市 岗位 列表
     * @return 公司列表
     * @author JacksonZHR
     */
    @Override
    public List<CompanyListData> relateCompany(int flag, CityJobChoiceListDTO cityJobChoiceListDTO) throws IOException, InterruptedException {
        List<String> choiceList = cityJobChoiceListDTO.getChoiceList();
        if (choiceList == null) {
            Criteria criteria = new Criteria("jobName").is(cityJobChoiceListDTO.getJobName()).and("region").is(cityJobChoiceListDTO.getCity());
            Query query = new Query(criteria);
            return mongoTemplate.find(query, CompanyListData.class);
        }

        String mainValue = null;
        String mainKey = null;
        String listKey = null;
        if (flag == 0) {
            mainKey = "region";
            mainValue = cityJobChoiceListDTO.getCity();
            listKey = "jobName";
        } else {
            mainKey = "jobName";
            mainValue = cityJobChoiceListDTO.getJobName();
            listKey = "region";
            choiceList.add("全国");
        }

        Criteria mainCriteria = new Criteria(mainKey).is(mainValue);
        Criteria listCriteria = Criteria.where(listKey).in(choiceList);
        Query query = new Query();
        query.addCriteria(mainCriteria).addCriteria(listCriteria);
        return mongoTemplate.find(query, CompanyListData.class);

//        String jobName = cityJobChoiceListDTO.getJobName();
//        String city = cityJobChoiceListDTO.getCity();
//        List<CompanyListData> companyListDataArrayList = new ArrayList<>();
//
//        StringBuilder pythonCommand = new StringBuilder();
//        //TODO ZHR [2024.01.03] 不要在此处校验
//        String temp;
//        if (choiceList == null) {
//            if (flag == 0) temp = jobName;
//            else temp = city;
//        }
//        else if(!choiceList.isEmpty()) {
//            temp = choiceList.get(0);
//        }
//        else {
//            if (flag == 0) temp = jobName;
//            else temp = city;
//        }
//
//        if (flag == 0) {
//            pythonCommand.append(PythonProcessUtil.generatePythonCommand(FilepathConfiguration.pyDirPath, FilepathConfiguration.pyName,
//                    CommandPatternEnum.RELATED_COMPANY_JOB, CommandCode.COMPANY.getOptionCode(), city, jobName, "0", temp));
//        } else if (flag == 1) {
//            pythonCommand.append(PythonProcessUtil.generatePythonCommand(FilepathConfiguration.pyDirPath, FilepathConfiguration.pyName,
//                    CommandPatternEnum.RELATED_COMPANY_REGION, CommandCode.COMPANY.getOptionCode(), city, jobName, "1", temp));
//        }
//
//        // TODO ZHR [2023.12.27] 对拼接字符串的命令的改进
//        if (choiceList != null) {
//            for (int i = 1; i < choiceList.size(); i++) {
//                pythonCommand.append(" ").append(choiceList.get(i));
//            }
//        }
//
//        String output = PythonProcessUtil.startPythonProcess(pythonCommand.toString());
//        String jsonFromPythonOutput = PythonJsonUtil.getJsonFromPythonOutput(output);
//
//        if (PythonJsonUtil.jsonExists(jsonFromPythonOutput)) {
//            Map<String, Object> stringObjectMap = PythonJsonUtil.jsonToMap(jsonFromPythonOutput);
//            if (flag == 0) {
//                for (String jobKey : stringObjectMap.keySet()) {
//                    List<String> list = (List<String>) stringObjectMap.get(jobKey);
//                    companyListDataArrayList.add(new CompanyListData(city, jobKey, list));
//                }
//            } else {
//                for (String regionKey : stringObjectMap.keySet()) {
//                    List<String> list = (List<String>) stringObjectMap.get(regionKey);
//                    companyListDataArrayList.add(new CompanyListData(regionKey, jobName, list));
//                }
//            }
//            return companyListDataArrayList;
//
//        } else return null;
    }

    @Override
    public CompanyInfoData getCompanyInfo(String companyName) throws IOException, InterruptedException {
//        String pythonCommand = PythonProcessUtil.generatePythonCommand(FilepathConfiguration.pyDirPath, FilepathConfiguration.pyName,
//                CommandPatternEnum.COMPANY_INFO, "3", companyName);
//        String output = PythonProcessUtil.startPythonProcess(pythonCommand);
//        String jsonFromPythonOutput = PythonJsonUtil.getJsonFromPythonOutput(output);
//        CompanyInfoData companyInfoData = JSONObject.parseObject(jsonFromPythonOutput, CompanyInfoData.class);

        Criteria criteria = Criteria.where("name").is(companyName);
        Query query = new Query(criteria);
        CompanyInfoData companyInfoData = mongoTemplate.findOne(query, CompanyInfoData.class);

        // 归一化
        if (companyInfoData != null) {
            Double sum = (double) 0;
            for (CompanyInfoData.TechData tech : companyInfoData.getTech()) {
                sum += tech.getRate();
            }
            for (CompanyInfoData.TechData tech : companyInfoData.getTech()) {
                tech.setRate(tech.getRate()/sum);
            }

        }

        return companyInfoData;

    }

    @Override
    public JSONArray getPositionRecommendationFromResume(Long userId) throws IOException, InterruptedException {
        // 删除历史数据
        QueryWrapper<PositionRecommendation> queryWrapperForDelete = new QueryWrapper<>();
        queryWrapperForDelete.eq("user_id", userId);
        positionRecommendationMapper.delete(queryWrapperForDelete);
        // 启动python
        String pythonCommand = PythonProcessUtil.generatePythonCommand(FilepathConfiguration.pyDirPath2, FilepathConfiguration.pyName,
                CommandPatternEnum.POSITION_RECOMMENDATION_FROM_RESUME, String.valueOf(userId));
        PythonProcessUtil.startPythonProcess(pythonCommand);

        //获取新的数据
        QueryWrapper<PositionRecommendation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        PositionRecommendation positionRecommendation = positionRecommendationMapper.selectOne(queryWrapper);
        if (positionRecommendation == null) return null;
        return positionRecommendation.getRecommendPosition();

    }

    @Override
    public List<CompetenceInfo> getCompetenceScore(Long userId) throws IOException, InterruptedException {
        // 删除历史数据
        QueryWrapper<CompetenceInfo> queryWrapperForDelete = new QueryWrapper<>();
        queryWrapperForDelete.eq("user_id", userId);
        competenceInfoMapper.delete(queryWrapperForDelete);
        // 启动python
        String pythonCommand = PythonProcessUtil.generatePythonCommand(FilepathConfiguration.pyDirPath2, FilepathConfiguration.pyName,
                CommandPatternEnum.COMPETENCE_INFO, String.valueOf(userId));
        PythonProcessUtil.startPythonProcess(pythonCommand);
        // 获取新的数据
        QueryWrapper<CompetenceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("direction", "match_skills", "score","rec_skills","suggestions").eq("user_id", userId);
        return competenceInfoMapper.selectList(queryWrapper);
    }

    @Override
    public JSONArray getDirectionFromInterestScore(Long userId) throws IOException, InterruptedException {
        // 删除历史数据
        QueryWrapper<DirectionRecommendation> queryWrapperForDelete = new QueryWrapper<>();
        queryWrapperForDelete.eq("user_id", userId);
        directionRecommendationMapper.delete(queryWrapperForDelete);
        // 启动python
        String pythonCommand = PythonProcessUtil.generatePythonCommand(FilepathConfiguration.pyDirPath3, FilepathConfiguration.pyName,
                CommandPatternEnum.POSITION_RECOMMENDATION_FROM_INTEREST, String.valueOf(userId));
        PythonProcessUtil.startPythonProcess(pythonCommand);

        //获取新的数据
        QueryWrapper<DirectionRecommendation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        DirectionRecommendation directionRecommendation = directionRecommendationMapper.selectOne(queryWrapper);
        if (directionRecommendation == null) return null;
        return directionRecommendation.getRecommendDirection();
    }

}
